package csu.web.mypetstore.web.servlet;
//搜索框

import csu.web.mypetstore.domain.Product;
import csu.web.mypetstore.service.CatalogService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "SearchProductFormServlet", urlPatterns = {"/searchProductForm"})
public class SearchProductFormServlet extends HttpServlet {

    public List<Product> productList;//Product列表
    public CatalogService catalogService;
    private String searchErrorMsg = null;//错误信息
    private static final String SEARCH_PRODUCT_FORM = "/WEB-INF/jsp/catalog/searchProducts.jsp";

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获得keywords
        HttpSession session = req.getSession();
        String keywords = req.getParameter("keywords");
//        System.out.println("search");
//        System.out.println(keywords);


        if (keywords == null || keywords.length() < 1) {
            searchErrorMsg = "请输入关键词";
        } else {
            catalogService = new CatalogService();
            productList = catalogService.searchProductList(keywords.toLowerCase());
            //将productList放入session供jsp获得
            session.setAttribute("productList", productList);

            session.setAttribute("action","searching");

            req.getRequestDispatcher(SEARCH_PRODUCT_FORM).forward(req, resp);
        }


    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }
}
